package com.syg.apiversion;

import com.syg.apiversion.annotation.ApiVersion;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Objects;

public class ApiVersionRequestMappingHandlerMapping  extends RequestMappingHandlerMapping {
    public ApiVersionRequestMappingHandlerMapping() {
    }

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion apiVersion = (ApiVersion) AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return this.createRequestCondition(apiVersion);
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        ApiVersion apiVersion = (ApiVersion)AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return this.createRequestCondition(apiVersion);
    }

    private RequestCondition<ApiVersionRequestCondition> createRequestCondition(ApiVersion apiVersion) {
        if (Objects.isNull(apiVersion)) {
            return null;
        } else {
            String value = apiVersion.value();
            return StringUtils.isEmpty(value) ? null : new ApiVersionRequestCondition(value);
        }
    }
}
